const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')
const ErrorResult = require('../config/handle')
const {getSecretKey} = require("./jwt");

class Auth {
  constructor() {
  }

  // 取值函数 set: 存值函数
  get m() {
    return async (ctx, next) => {
      const token = basicAuth(ctx.req)
      if (!token || !token.name) {
        throw new ErrorResult({errorCode: '401', msg: '没有访问权限'}, 401)
      }
      try {
        const {userId} = jwt.verify(token.name, getSecretKey())
        ctx.auth = {
          uid: userId
        }
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          throw new ErrorResult({errorCode: '401', msg: 'token已过期'}, 401)
        }
        throw new ErrorResult({errorCode: '401', msg: '没有访问权限'}, 401)
      }
      await next()
    }
  }

  // get m() {
  //   return async (ctx, next) => {
  //     const token = ctx.request.header.authorization
  //     if (!token) {
  //       throw new ErrorResult({errorCode: '401', msg: '没有访问权限'}, 401)
  //     }
  //     try {
  //       const {userId} = jwt.verify(token, getSecretKey())
  //       console.log(userId)
  //       ctx.auth = {
  //         userId,
  //       }
  //     } catch (error) {
  //       if (error.name === 'TokenExpiredError') {
  //         throw new ErrorResult({errorCode: '401', msg: 'token已过期'}, 401)
  //       }
  //       throw new ErrorResult({errorCode: '401', msg: '没有访问权限'}, 401)
  //     }
  //     await next()
  //   }
  // }
}

module.exports = Auth